package com.example.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.example.common.enums.RoleEnum;
import com.example.entity.Employee;
import com.example.entity.Expenses;
import com.example.entity.ProcessingRecords;
import com.example.mapper.ProcessingRecordsMapper;
import com.example.service.EmployeeService;
import com.example.service.ExpensesService;
import com.example.service.ProcessingRecordsService;
import com.example.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author dingchunlin
 * @Date 2023/11/8 12:06
 * @Version 1.0.0
 */
@Service
public class ProcessingRecordsServiceImpl extends ServiceImpl<ProcessingRecordsMapper, ProcessingRecords> implements ProcessingRecordsService {

    @Autowired
    private ProcessingRecordsMapper processingRecordsMapper;

    @Autowired
    private ExpensesService expensesService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private ProcessingRecordsService processingRecordsService;

    /**
     * 新增
     *
     * @param processingRecords
     */
    @Override
    public void add(ProcessingRecords processingRecords) {
        processingRecords.setCreateTime(LocalDateTime.now());
        processingRecords.setProcessingResult("审核中");
        processingRecordsMapper.insert(processingRecords);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        processingRecordsMapper.deleteById(id);
    }

    @Override
    public void deleteByExpenseId(Integer id) {
        LambdaQueryWrapper<ProcessingRecords> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProcessingRecords::getExpenseId, id);
        processingRecordsMapper.delete(lambdaQueryWrapper);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            processingRecordsMapper.deleteById(id);
        }
    }

    /**
     * 修改
     *
     * @param processingRecords
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProcessingRecords(ProcessingRecords processingRecords) {
        //这个是报销单
        Expenses expenses = processingRecords.getExpenses();
        //先修改当前报销单审核的状态
        processingRecords.setProcessingTime(LocalDateTime.now());
        baseMapper.updateById(processingRecords);

        //如果金额不大于5000且审核通过,修改报销单的状态
        if (expenses.getTotalAmount() < 5000 ){
            expenses.setStatus(processingRecords.getProcessingResult());
            expensesService.updateExpensesById(expenses);
        }
        Employee employee = employeeService.selectByDepartmentIdAndRole(0, RoleEnum.GENERAL_MANAGER.name());
        Employee token = TokenUtils.getCurrentUser();
        if (!token.getId().equals(employee.getId())) {
            //如果报销单金额大于5000给总经理进行审核
            if ("审核通过".equals(processingRecords.getProcessingResult()) && expenses.getTotalAmount() > 5000 && processingRecords.getHandlerId() != employee.getId()){
                //查询出总经理的id
                //添加审核单
                ProcessingRecords add = new ProcessingRecords();
                add.setExpenseId(expenses.getId());
                add.setHandlerId(employee.getId());
                add.setProcessingType(expenses.getExpensesType());
                processingRecordsService.add(add);
            }
        }
        if (token.getId().equals(employee.getId())) {
            //如果报销单金额大于5000给总经理进行审核
            expenses.setStatus(processingRecords.getProcessingResult());
            expensesService.updateExpensesById(expenses);
        }

    }

    /**
     * 根据ID查询
     *
     * @param id
     */
    @Override
    public ProcessingRecords selectById(Integer id) {
        return processingRecordsMapper.selectById(id);
    }

    /**
     * 查询所有
     *
     * @param processingRecords
     */
    @Override
    public List<ProcessingRecords> selectAll(ProcessingRecords processingRecords) {
        LambdaQueryWrapper<ProcessingRecords> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(ProcessingRecords::getId);
        if (ObjectUtil.isNotEmpty(processingRecords.getExpenseId())){
            lambdaQueryWrapper.eq(ProcessingRecords::getExpenseId,processingRecords.getExpenseId());
        }
        List<ProcessingRecords> processingRecordsList = processingRecordsMapper.selectList(lambdaQueryWrapper);
        processingRecordsList.forEach( item ->{
            Employee employee = employeeService.selectById(item.getHandlerId());
            item.setHandlerName(employee.getName());
        });
        return processingRecordsList;
    }

    /**
     * 分页查询
     *
     * @param processingRecords
     * @param pageNum
     * @param pageSize
     */
    @Override
    public PageInfo<ProcessingRecords> selectPage(ProcessingRecords processingRecords, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProcessingRecords> list = selectAll(processingRecords);
        return PageInfo.of(list);
    }

    @Override
    public PageInfo<ProcessingRecords> getExpensesById(Integer pageNum, Integer pageSize,String expensesType) {
        Employee employee = TokenUtils.getCurrentUser();
        Integer id = employee.getId();
        PageHelper.startPage(pageNum, pageSize);
        LambdaQueryWrapper<ProcessingRecords> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProcessingRecords::getHandlerId,id);
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(expensesType),ProcessingRecords::getProcessingType,expensesType);
        List<ProcessingRecords> processingRecords = baseMapper.selectList(lambdaQueryWrapper);
        processingRecords.forEach( item ->{
            Integer expenseId = item.getExpenseId();
            Expenses expenses = expensesService.selectById(expenseId);
            if (ObjectUtil.isNotEmpty(expenses)){
                item.setExpenses(expenses);
            }
        });
        return PageInfo.of(processingRecords);
    }

    @Override
    public ProcessingRecords selectByProcessingRecords(ProcessingRecords records) {
        LambdaQueryWrapper<ProcessingRecords> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(records.getExpenseId()),ProcessingRecords::getExpenseId,records.getExpenseId());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(records.getHandlerId()),ProcessingRecords::getHandlerId,records.getHandlerId());
        ProcessingRecords processingRecords = processingRecordsMapper.selectOne(lambdaQueryWrapper);
        return processingRecords;
    }
}
